import { Space } from 'antd';
import { forwardRef, useImperativeHandle } from 'react';
import { useSafeState, useMemoizedFn } from 'ahooks';
import MultiTool from '../MultiTool';
import type { ToolsProps } from './types';
import useConfigs from '../hooks/useConfigs';
import { ToolButtonWrapper } from '../ToolButton';
import ColorPickerPro from '@/components/ColorPickerPro';
import type { MultiToolResult } from '../MultiTool/types';

export type ToolsRef = {
  resetTool: () => void;
}

const Tools = forwardRef<ToolsRef, ToolsProps>((props, ref) => {
  const [toolConfigs] = useConfigs();
  const [tool, setTool] = useSafeState<MultiToolResult>();

  const handleClick = useMemoizedFn((res: MultiToolResult) => {
    setTool(res);
    props.onToolChange?.(res);
  });

  const resetTool = useMemoizedFn(() => {
    const [initTool] = toolConfigs;
    setTool({ current: initTool });
  });

  useImperativeHandle(ref, () => {
    return { resetTool };
  });

  return (
    <Space size={20} direction="vertical">
      {toolConfigs.map(config => {
        const current = tool?.current;
        return (
          <MultiTool
            key={config.id}
            config={config}
            onClick={handleClick}
            selected={config.id === current?.id}
          />
        );
      })}
      <ToolButtonWrapper
        tooltip="填充颜色"
        enableHover={false}
      >
        <ColorPickerPro
          value={props.fill}
          onChange={props.onFillChange}
        />
      </ToolButtonWrapper>
      <ToolButtonWrapper
        tooltip="边框颜色"
        enableHover={false}
      >
        <ColorPickerPro
          value={props.stroke}
          onChange={props.onStrokeChange}
        />
      </ToolButtonWrapper>
    </Space>
  );
});

export default Tools;